import { defineStore } from 'pinia';
import { getUserProfile } from '@/api/auth';

interface UserInfo {
  customerId: number;
  phone: string;
  nickname: string;
  avatar: string;
  address: string;
  regionId: number;
}

interface UserState {
  token: string;
  isLogin: boolean;
  userInfo: UserInfo | null;
}

export const useUserStore = defineStore('user', {
  state: (): UserState => ({
    token: '',
    isLogin: false,
    userInfo: null
  }),

  getters: {
    // 是否已登录
    hasLogin: (state) => state.isLogin && !!state.token,
    
    // 格式化后的手机号
    formatPhone: (state) => {
      if (!state.userInfo?.phone) return '';
      return state.userInfo.phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2');
    }
  },

  actions: {
    // 设置 token
    setToken(token: string) {
      this.token = token;
      this.isLogin = !!token;
    },

    // 设置用户信息
    setUserInfo(userInfo: UserInfo) {
      this.userInfo = userInfo;
    },

    // 登录
    async login(token: string, userInfo: UserInfo) {
      this.setToken(token);
      this.setUserInfo(userInfo);
    },

    // 获取用户信息
    async fetchUserInfo() {
      if (!this.userInfo?.customerId) return;
      
      try {
        const data: any = await getUserProfile(this.userInfo.customerId);
        this.setUserInfo({
          customerId: this.userInfo.customerId,
          phone: data.phoneNumber || this.userInfo.phone,
          nickname: data.nickname || this.userInfo.nickname,
          avatar: data.avatarUrl || this.userInfo.avatar,
          address: data.address || this.userInfo.address,
          regionId: data.regionId || this.userInfo.regionId
        });
        console.log('用户信息已更新', this.userInfo)
      } catch (error) {
        console.error('获取用户信息失败:', error);
      }
    },

    // 退出登录
    logout() {
      this.token = '';
      this.isLogin = false;
      this.userInfo = null;
      
      // 清除本地存储
      uni.removeStorageSync('token');
      uni.removeStorageSync('userInfo');
      
      console.log('用户已退出登录');
    }
  },

  // 开启持久化
  persist: true
});